'use strict';

const bcrypt = require('bcryptjs');

module.exports = (app) => {
    const mongoose = app.mongoose;
    const Schema = mongoose.Schema;

    const UserSchema = new Schema({
        username: {
            type: String,
            unique: true,
            require: true,
            index: 1
        },
        password: {
            type: String,
            require: true
        },
        // 是否为超级管理员
        root: {
            type: Boolean,
            default: false
        },
        name: {
            type: String,
            default: ''
        },
        headImg: {
            type: String,
            default: 'https://lvyueyang-blog.oss-cn-beijing.aliyuncs.com/user/5ae1eede93b63b243c71f5ab.gif'
        },
        phone: {
            type: String,
            default: ''
        },
        sex: {
            type: String,
            default: '未知'
        },
        email: {
            type: String,
            default: ''
        },
        qq: {
            type: String,
            default: ''
        },
        weixin: {
            type: String,
            default: ''
        },
        summary: {
            type: String,
            default: ''
        },
        token: {
            type: String,
            default: null,
            index: 1
        },
        role: [
            {
                type: Schema.Types.ObjectId,
                ref: 'role'
            }
        ],
        status: {
            type: Number,
            default: 1,     //  0删除 1正常 2封禁
        },
        createAt: {
            type: Date,
            default: Date.now
        },
        updateAt: {
            type: Date,
            default: Date.now
        }
    });

    // 对密码进行加密处理
    UserSchema.pre('save', function (next) {
        let user = this;
        
        if (!user.name) {
            user.name = '用户' + user.username;
        }
        bcrypt.genSalt(10, function (err, salt) {
            if (err) {
                console.log('加密失败');
                return next(err);
            }
            bcrypt.hash(user.password, salt, function (err, hash) {
                if (err) {
                    return next(err);
                }
                user.password = hash;
                next();
            });
        });
    });

    return mongoose.model('user', UserSchema);
};
